package com.example.myapplication.ui.expenses;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.myapplication.App;
import com.example.myapplication.MainActivity;
import com.example.myapplication.R;
import com.example.myapplication.entity.Budget;
import com.example.myapplication.entity.Income;
import com.example.myapplication.entity.Pay;
import com.example.myapplication.greendao.BudgetDao;
import com.example.myapplication.greendao.DaoSession;
import com.example.myapplication.greendao.IncomeDao;
import com.example.myapplication.greendao.PayDao;
import com.example.myapplication.ui.income.IncomeFragment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ExpensesFragment extends Fragment {
    private Button b1,b2, b4;
    private App app;
    private DaoSession daoSession;
    private Spinner spinner;
    private String element;
    private int s_position;
    private String payType;
    double currentPay = 0;
    private int startYear, startMonth, startDay;
    private Calendar calendar;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_expenses, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        calendar = Calendar.getInstance();
        startYear = calendar.get(Calendar.YEAR);
        startMonth = calendar.get(Calendar.MONTH);
        startDay = calendar.get(Calendar.DAY_OF_MONTH);
        b1 = getActivity().findViewById(R.id.button_add);
        b2 = getActivity().findViewById(R.id.payTime);
        b4 = getActivity().findViewById(R.id.button_look);
        spinner = getActivity().findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(new OnItemSelectedListenerImpl());
        setListeners();
    }

    private class Onclick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_add:
                    app = (App) getActivity().getApplication();
                    daoSession = app.getDaoSession();
                    EditText t1 = getActivity().findViewById(R.id.text_1);
                    EditText t2 = getActivity().findViewById(R.id.text_2);
                    PayDao payDao = daoSession.getPayDao();
//                    Date date = new Date();//此时date为当前的时间
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                    Date date = null;
                    try {
                        date = df.parse(String.valueOf(b2.getText()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    double payVal = Double.parseDouble(t1.getText().toString());
                    //有预期的话检查花费是否超过预期
                    BudgetDao budgetDao = daoSession.getBudgetDao();
                    List<Budget> daoList = budgetDao.loadAll();
                    Time t=new Time();
                    t.setToNow();
                    int currentYear = t.year;
                    int currentMonth = t.month+1;
                    for (Budget dao1:daoList){
                        Date datDate = dao1.getBudgetDate();
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(datDate);
                        int DaoYear = cal.get(Calendar.YEAR);//获取年份
                        int DaoMonth=cal.get(Calendar.MONTH);//获取月份
                        //System.out.println(DaoYear + " " +DaoMonth);
                        if (DaoYear==currentYear && DaoMonth==currentMonth){
                            System.out.println("有匹配值");
                            //有匹配值,查找本月支出情况
                            Double limit = null;
                            switch (payType){
                                case "life":
                                    limit = dao1.getLife();
                                    break;
                                case "travel":
                                    limit = dao1.getTravel();
                                    break;
                                case "food":
                                    limit = dao1.getFood();
                                    break;
                                case "fun":
                                    limit = dao1.getFun();
                                    break;
                                case "learn":
                                    limit = dao1.getLearn();
                                    break;
                                case "close":
                                    limit = dao1.getClose();
                                    break;
                            }
                            System.out.println("限制为："+limit);
                            PayDao payDao1 = daoSession.getPayDao();
                            List<Pay> payList = payDao1.loadAll();
                            currentPay = 0;
                            for (Pay pay:payList) {
                                Calendar cal1 = Calendar.getInstance();
                                cal1.setTime(pay.getPayDate());
                                int payYear = cal1.get(Calendar.YEAR);//获取年份
                                int payMonth=cal1.get(Calendar.MONTH)+1;//获取月份
                                if (payYear==currentYear && payMonth==currentMonth){
                                    //是这个月的消费
                                    if (pay.getPayType().equals(payType)){
                                        currentPay += pay.getPay();
                                    }
                                }
                            }
                            System.out.println("本月消费了"+currentPay);
                            if (currentPay+payVal>limit){
                                //超出限制
                                Toast.makeText(getContext(), "本月此类型消费过多，已超预算", Toast.LENGTH_SHORT).show();
                                return;
                            }else {
                                System.out.println("可以消费");
                            }
                            break;
                        }
                    }
                    System.out.println("进行插入！");
                    String remark = t2.getText().toString();
                    Pay pay = new Pay();
                    pay.setPay(payVal);
                    pay.setPayRemarks(remark);
                    pay.setPayType(payType);
                    pay.setPayDate(date);
                    payDao.insert(pay);
                    Toast.makeText(getContext(), "插入成功", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.button_look:
                    app = (App) getActivity().getApplication();
                    daoSession = app.getDaoSession();
                    PayDao payDao1 = daoSession.getPayDao();
                    List<Pay> payList = payDao1.loadAll();
                    ListView listView = getActivity().findViewById(R.id.list);
                    List<String> list = new ArrayList<String>();
                    for (Pay pay1 : payList) {
                        list.add("支出：" + pay1.getPay() + " " + "支出说明：" + pay1.getPayRemarks() + " " + "支出类型：" + pay1.getPayType() + " " + "时间：" + pay1.getPayDate());
                    }
                    ///可以一直添加，在真机运行后可以下拉列表
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, list);
                    listView.setAdapter(adapter);
                    break;
                case R.id.payTime:
                    new DatePickerDialog(getContext(),
                            startSetListener, startYear, startMonth, startDay).show();
                    break;
            }
        }
    }

    private DatePickerDialog.OnDateSetListener startSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            startYear = year;
            startMonth = monthOfYear;
            startDay = dayOfMonth;
            //更新Button上显示的日期
            updateDateStartDisplay();
        }
    };

    private void updateDateStartDisplay() {
        b2.setText(new StringBuilder().append(startYear).append("-")
                .append(startMonth + 1).append("-").append(startDay));
    }

    // 下拉框选择事件
    private class OnItemSelectedListenerImpl implements AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            element = parent.getItemAtPosition(position).toString();// 得到spanner的值
            s_position = position;
            switch (s_position) {
                case 0:
                    payType = "life";
                    break;
                case 1:
                    payType = "travel";
                    break;
                case 2:
                    payType = "food";
                    break;
                case 3:
                    payType = "fun";
                    break;
                case 4:
                    payType = "learn";
                    break;
                case 5:
                    payType = "close";
                    break;

            }
            Toast.makeText(getActivity(), "选择的元素是：" +
                    element, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }
    }


    private void setListeners() {
        Onclick onclick = new Onclick();
        b1.setOnClickListener(onclick);
        b2.setOnClickListener(onclick);
        b4.setOnClickListener(onclick);
    }
}
